package com.example.controller;

import com.example.common.Result;
import com.example.entity.ExamPaper;
import com.example.mapper.ExamManualQuestionMapper;
import com.example.service.ExamPaperService;
import com.example.dto.ExamPaperDTO;
import com.example.vo.ExamPaperDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/examPapers")
public class ExamPaperController {

    @Autowired
    private ExamPaperService examPaperService;

    @Autowired
    ExamManualQuestionMapper examManualQuestionMapper;



    // 新增试卷
    @PostMapping
    public Result addExamPaper(@RequestBody ExamPaperDTO examPaperDTO) {
        examPaperService.addExamPaper(examPaperDTO);
        return Result.success();
    }

    // 更新试卷
    @PutMapping("/{id}")
    public Result updateExamPaper(@PathVariable Integer id, @RequestBody ExamPaperDTO examPaperDTO) {
        examPaperDTO.setPaperId(id);
        examPaperService.updateExamPaper(examPaperDTO);

        return Result.success();
    }

    // 删除试卷
    @DeleteMapping("/{id}")
    public Result deleteExamPaperById(@PathVariable Integer id) {
        examPaperService.deleteExamPaperById(id);
        return Result.success();
    }

    // 分页查询
    @GetMapping("/page")
    public Result<Map<String, Object>> getExamPapersByPage( @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        // 调用服务层获取分页数据
        List<ExamPaper> examPapers = examPaperService.getExamPapersByPage(pageNum, pageSize);
        examPapers.forEach(examPaper -> {
            Integer paperId = examPaper.getId();
            int size = examManualQuestionMapper.selectExamManualQuestionsByQsnairId(paperId).size();
            examPaper.setTotalQuestions(size);
        });
        
        // 获取总记录数
        long total = examPaperService.getTotalExamPapers();
        long totalPages = (total + pageSize - 1) / pageSize; // 计算总页数
        
        result.put("total", total);
        result.put("totalPages", totalPages);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("items", examPapers);
        
        return Result.success(result);
    }


    //  根据试卷ID获取试卷详情
    @GetMapping("/detail/{id}")
    public Result<ExamPaperDetailVO> getExamPaperDetail(@PathVariable Integer id) {
        ExamPaperDetailVO examPaperDetail = examPaperService.getExamPaperDetailById(id);
        return Result.success(examPaperDetail);
    }

}
